package com.violet.uaa.server.security.handler;

import cn.hutool.json.JSONUtil;
import com.violet.common.entity.LoginUser;
import com.violet.common.response.Result;
import com.violet.uaa.server.login.entity.LoginLog;
import com.violet.uaa.server.login.service.LoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * 类说明: spring security 自定义退出登录
 *
 * @author wqf
 * @date 2022/6/8 17:09
 */
@Slf4j
@Component
public class VioLogOutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private LoginLogService loginLogService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        try {
            if (authentication != null) {
                LoginLog loginLog = new LoginLog();
                LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                loginLog.setUsername(loginUser.getUsername());
                loginLog.setIp(request.getRemoteAddr());
                loginLog.setOperateTime(LocalDateTime.now());
                loginLog.setRemark("用户登出");
                loginLogService.save(loginLog);
                log.error("=========用户登出日志记录成功========{}", JSONUtil.toJsonStr(loginLog));
            }else{
                log.warn("===========当前用户权限认证信息为空===========");
            }
        } catch (Exception e) {
            log.error("=========用户登出日志记录失败========", e);
        }
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try (ServletOutputStream ous = response.getOutputStream()) {
            Result<Object> responseData = Result.succeed("登出成功");
            response.setStatus(HttpStatus.OK.value());
            ous.write(JSONUtil.toJsonStr(responseData).getBytes(StandardCharsets.UTF_8));
        }
    }
}